﻿using System.Collections;

namespace Microsoft.AspNetCore.App
{
    /// <summary>
    /// 特征：用于保存中间件过程中的数据
    /// </summary>
    public interface IFeatureCollection : IEnumerable<KeyValuePair<Type, object?>>
    {
        TFeature? Get<TFeature>()
            where TFeature : class;

        void Set<TFeature>(TFeature? instance)
            where TFeature : class;
    }

    public class FeatureCollection : IFeatureCollection
    {
        private readonly Dictionary<Type, object?> _features = new();

        public FeatureCollection()
        {

        }

        public TFeature? Get<TFeature>()
            where TFeature : class
        {
            _features.TryGetValue(typeof(TFeature), out var instance);
            return instance as TFeature;
        }

        public IEnumerator<KeyValuePair<Type, object?>> GetEnumerator()
        {
            return _features.GetEnumerator();
        }

        public void Set<TFeature>(TFeature? instance)
             where TFeature : class
        {
            _features.TryAdd(typeof(TFeature), instance);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable)_features).GetEnumerator();
        }
    }
}
